package Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import models.service;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class GetOpalServiceList {

	
	private static Document dom;
	private static List<service>  serviceList= new ArrayList<service>();

	
	static String pipe(InputStream in,String charset) throws IOException {
        StringBuffer s = new StringBuffer();
        if(charset==null||"".equals(charset)){
        	charset="utf-8";
        }
        String rLine = null;
        BufferedReader bReader = new BufferedReader(new InputStreamReader(in,charset));
        PrintWriter pw = null;
        
		FileOutputStream fo = new FileOutputStream("../index.html");
		OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8");
		pw = new PrintWriter(writer);
        while ( (rLine = bReader.readLine()) != null) {
            String tmp_rLine = rLine;
            int str_len = tmp_rLine.length();
            if (str_len > 0) {
              s.append(tmp_rLine);
              pw.println(tmp_rLine);
              pw.flush();
            }
            tmp_rLine = null;
       }
        in.close();
        pw.close();
        return s.toString();
	}
	
	//get xml file
	public String crawler (String a) throws IOException
	{
		String str = null;
		String res = null; 		
		URL link001 = new URL(a);
			
		HttpURLConnection conn_1 =  (HttpURLConnection)(link001.openConnection());
		conn_1.setRequestMethod("GET");
		conn_1.connect();
			
		BufferedReader br_1 = new BufferedReader(new InputStreamReader(conn_1.getInputStream()));		
		while ((str = br_1.readLine()) != null) 
		{
			res += str;		
		}	
		return res;
	}
	
	
	private static void parseServiveListXmlFile(String location){
		//get the factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try {
			
			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			//parse using builder to get DOM representation of the XML file
			//dom = db.parse(location);
			
			dom = db.parse(new InputSource(location));
		

		    

		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	//add srv into list
	private static void addtolist(String servicename,String serviceURL,String serviceSummary){
		service srv = new service(servicename,serviceURL,serviceSummary);
		serviceList.add(srv);
	}
	
	//clear srvlist -- for reset
	private static void resetlist(){
		serviceList = new ArrayList<service>();;
	}
	
	//parse the xml
	private static void parseServiceListDocument(){
		
		resetlist();
		//get the root elememt
		Element docEle = dom.getDocumentElement();
		
		//get a nodelist of <employee> elements
		NodeList nl = docEle.getElementsByTagName("entry");
		
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {
				String servicename ="";
				String serviceURL ="";
				String serviceSummary="";
				//get the employee element
				Element el = (Element)nl.item(i);
				
				//get server names!!!!!
				NodeList servernameNL =  el.getElementsByTagName("title");
				if(nl != null && nl.getLength() > 0) {
					Element ele = (Element)servernameNL.item(0);
					servicename = ele.getFirstChild().getNodeValue();
					//System.err.println("title: "+servicename);
				}
				
				//get server urls!!!!!
				NodeList serverurlNL =  el.getElementsByTagName("link");
				if(nl != null && nl.getLength() > 0) {
					Element ele = (Element)serverurlNL.item(0);
					serviceURL = ele.getAttribute("href");
				}
				//get server authors!!!!! !!!!!!!need to fix!!!
				NodeList serverauthorNL =  el.getElementsByTagName("author");
				if(nl != null && nl.getLength() > 0) {
					String serviceAuthor ="";
					Element ele = (Element)serverauthorNL.item(0);
					NodeList nameNL = ele.getElementsByTagName("name");
					if(nameNL != null && nameNL.getLength() > 0) {
						Element ele2 = (Element)nameNL.item(0);
						try{
							serviceAuthor = ele2.getFirstChild().getNodeValue();
						}catch(Exception e){
							serviceAuthor = "no author";
						}
					}
				}
				
				//get server summary!!!!!
				NodeList serverSmyNL =  el.getElementsByTagName("summary");
				if(nl != null && nl.getLength() > 0) {
					Element ele = (Element)serverSmyNL.item(0);
					serviceSummary = ele.getFirstChild().getNodeValue();
				}
				
				addtolist(servicename, serviceURL, serviceSummary);

				
			}
		}
	}
	
	//get service list from the link.
	public void dogetlist(String link){
		link = "http://ws.nbcr.net/opal2/opalServices.xml";
        String result = ""; 
        
        
		try {
			result = crawler(link);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        result = result.substring(4);

		try {
			PrintStream outfile = new PrintStream(new FileOutputStream(new File("a.xml")));
			outfile.println(result);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		parseServiveListXmlFile("a.xml");
		parseServiceListDocument();
		
		
	}

	public static List<service> getServiceList() {
		return serviceList;
	}

	public static void setServiceList(List<service> serviceList) {
		GetOpalServiceList.serviceList = serviceList;
	}


	
	
}
